import { useState, useEffect, useMemo, useRef } from 'react';
import { Button, Checkbox, Popover } from 'antd';
import { find, uniqBy } from 'lodash';
import CommonModal from '@/components/CommonModal';
import CommonTable from '@/components/CommonTable';
import CommonPagination from '@/components/CommonPagination';
import CommonLoading from '@/components/CommonLoading';
import ModalForm from './ModalForm';
import { getTableDataOp, queryIsOpenOfflinePay } from './service';

const initPagination = {
  current: 1,
  total: 0,
  pageSize: 100,
}

const merchantAreaCodeMap = {
  NT: '南通',
  CS: '常熟',
  ZL: '织里'
}

const AddSelectListModal = ({ visible, resetKey, storeList, outSelected, handleOk, handleCancel }) => {

  const [query, setQuery] = useState({});
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [pagination, setPages] = useState(null); //分页
  const [offlinePaymentShow, setOfflinePaymentShow] = useState(false); //是否展示线下支付字段

  const [selectedRowKeys, setSelectedRowKeys] = useState([]);//勾选项

  const [initKey, setInitKey] = useState(0);

  const totalSelect = useRef([]);

  useEffect(()=>{
    totalSelect.current = [];
    selectedRowKeys?.length && setSelectedRowKeys([]);
  },[resetKey])

  useEffect(() => {
    if (visible) {
      if(outSelected?.length){
        const list = outSelected.map(item=> find(storeList, ['storeId', item]));
        totalSelect.current = list;
        pagination.current = 1;
        pagination.total = outSelected?.length;
        setData(list);
        setSelectedRowKeys(outSelected)
      }else{
        totalSelect.current = [];
        selectedRowKeys?.length && setSelectedRowKeys([]);
        setQuery({});
      }
      return
      // getIsOpenOfflinePay();
      if (storeList?.length) {
        const newArr = storeList.filter(item => item.isSelect);
        totalSelect.current = newArr;
        const currentSelected = [];
        newArr.map(item => {
          const obj = find(data, ['storeId', item.storeId]);
          if (obj) {
            currentSelected.push(item.storeId);
          }
        })
        setSelectedRowKeys(currentSelected);
      }else{
        totalSelect.current = [];
        setSelectedRowKeys([]);
      }
    }else{
      setInitKey(initKey + 1);
    }
  }, [visible])

  useEffect(() => {
    setPages({
      ...(pagination || initPagination),
      current: 1
    })
  }, [query])

  useEffect(() => {
    if (pagination) {
      getTableListFunc();
    }
  }, [pagination])

  const getTableListFunc = async () => {
    setLoading(true);
    const params = {
      ...query,
      size: pagination.pageSize,
      current: pagination.current
    }
    const { data, success } = await getTableDataOp(params);
    if (success) {
      const { records = [], total = 0 } = data || {};
      pagination.total = total;
      const currentSelected = [];
      totalSelect.current.map(item => {
        const obj = find(records, ['storeId', item.storeId]);
        if (obj) {
          currentSelected.push(item.storeId);
        }
      })
      // console.log(currentSelected);
      setSelectedRowKeys(currentSelected);
      setData(records);
    }
    setLoading(false);
  }

  //检测是否开通线下支付
  const getIsOpenOfflinePay = async () => {
    const { data, success } = await queryIsOpenOfflinePay();
    if (success) {
      setOfflinePaymentShow(data);
    }
  };

  //全选反全选
  const handleAllCheck = (bool) => {
    const newArr = data.map(item => item.storeId);
    if (bool) {
      totalSelect.current = uniqBy([...new Set([...totalSelect.current, ...data])], 'storeId');
      setSelectedRowKeys(newArr);
    } else {
      const newArr1 = totalSelect.current.filter(item => !newArr.includes(item.storeId));
      totalSelect.current = newArr1;
      setSelectedRowKeys([]);
    }
  }

  //勾选取消勾选
  const handleSingleCheck = (bool, record) => {
    if (bool) {
      totalSelect.current = [...new Set([...totalSelect.current, record])];
      setSelectedRowKeys([...selectedRowKeys, record.storeId]);
    } else {
      const newArr1 = totalSelect.current.filter(item => item.storeId != record.storeId),
        newArr2 = selectedRowKeys.filter(item => item != record.storeId);
      totalSelect.current = newArr1;
      setSelectedRowKeys(newArr2);
    }
  }

  const frontColumns = [
    {
      title: (
        <><span>全选 </span><Checkbox
          checked={!!selectedRowKeys.length ? selectedRowKeys.length == data?.length : false}
          disabled={data?.length == 0}
          indeterminate={!!selectedRowKeys.length && (selectedRowKeys.length < data?.length)}
          onChange={(e) => handleAllCheck(e.target.checked)}
          className='allCheckedStyle'
        /></>
      ),
      width: 80,
      fixed: 'left',
      render: (_, record) => (
        <>
          &nbsp;&nbsp;<Checkbox
            checked={selectedRowKeys.includes(record.storeId)}
            onChange={(e) => handleSingleCheck(e.target.checked, record)}
          />
        </>
      ),
    },
    {
      title: '城市',
      dataIndex: 'merchantAreaCode',
      key: 'merchantAreaCode',
      width: 112,
      render: (text) => (<>{merchantAreaCodeMap[text]}</>),
    },
    {
      title: '供应商',
      dataIndex: 'storeName',
      key: 'storeName',
      width: 112,
    },
    {
      title: '门店名称',
      dataIndex: 'shopName',
      key: 'shopName',
      width: 240,
    },
    {
      title: '门店区域',
      dataIndex: 'storeArea',
      key: 'storeArea',
      width: 200,
    },
    {
      title: '门店编码',
      dataIndex: 'shopCode',
      key: 'shopCode',
      width: 140,
    },
    {
      title: '供应商类型',
      dataIndex: 'type',
      key: 'type',
      width: 120,
      render: text => (text == 1 ? '代发' : '供应商直发')
    },
    {
      title: '是否允许自动推送订单打印',
      dataIndex: 'autoPush',
      width: 220,
      render: text => (text == 1 ? '是' : '否')
    },
    {
      title: '门店地址',
      dataIndex: 'shopAddress',
      key: 'shopAddress',
      width: 220,
    },
    {
      title: '区域编码',
      dataIndex: 'shopArea',
      key: 'shopArea',
      width: 200,
    },
  ];

  const lastColumns = [
    {
      title: '门店备注',
      dataIndex: 'shopRemark',
      key: 'shopRemark',
      render: (_, record) => {
        return (
          <Popover
            content={
              <div className="custom-ant-popver-content">
                {record.shopRemark || ''}
              </div>
            }
          >
            <span className="textOverflowMultiTwo">
              {record.shopRemark || ''}
            </span>
          </Popover>
        );
      },
      width: 200,
    },
    {
      title: '拿货员',
      dataIndex: 'takeUser',
      key: 'takeUser',
      width: 120,
    },
    {
      title: '退货员',
      dataIndex: 'refundUser',
      key: 'refundUser',
      width: 120,
    },
  ]

  const columns = useMemo(() => {
    if (offlinePaymentShow) {
      return [
        ...frontColumns,
        {
          title: '线下支付',
          dataIndex: 'offlinePaySwitch',
          key: 'offlinePaySwitch',
          width: 120,
          render: (text, record) => text == 1 ? '是' : '否',
        },
        ...lastColumns
      ]
    } else {
      return [...frontColumns, ...lastColumns]
    }
  }, [offlinePaymentShow, data, selectedRowKeys])

  //表单组件
  const formProps = {
    initKey,
    offlinePaymentShow,
    handleSearch(val) {
      setQuery(val || {});
    },
    handleFilter(){
      pagination.current = 1;
      pagination.total = totalSelect.current.length;
      setSelectedRowKeys(totalSelect.current.reduce((prev,next)=>{
        return prev.concat(next.storeId)
      }, []))
      setData(totalSelect.current);
      setInitKey(initKey + 1);
    }
  }

  //表格组件  
  const tableProps = {
    data,
    columns,
    rowKey: 'storeId',
    scroll: { y: offlinePaymentShow ? 370 : 400 }
  }

  //分页props
  const pageProps = {
    pagination,
    handleChange(current, size) {
      setPages({
        ...pagination,
        current: pagination.pageSize == size ? current : 1,
        pageSize: size
      });
    },
  };

  //清空
  const handleClear = () => {
    totalSelect.current = [];
    setSelectedRowKeys([]);
  }

  //点击确定
  const onOK = () => {
    const arr = totalSelect.current.map(item=>{
      return {
        ...item,
        isSelect: true
      }
    })
    handleOk(arr);
  }

  return (<CommonModal
    title='选择所需筛选的供应商'
    visible={visible}
    onOk={onOK}
    onCancel={handleCancel}
    width='1092px'
  >
    <ModalForm {...formProps} />
    <CommonTable {...tableProps} />
    <div style={{ display: 'flex', justifyContent: 'space-between' }}>
      <div style={{ width: '280px', padding: "12px 24px 0 24px" }}>
        当前已选择 <span className="common-color9"> {totalSelect?.current?.length} </span> 条
        <Button type="link" onClick={handleClear}>清空</Button>
      </div>
      <div style={{ marginTop: '12px' }}>
        <CommonPagination {...pageProps} />
      </div>
    </div>
    <CommonLoading loading={loading} />
  </CommonModal>)
}

export default AddSelectListModal;